package com.wzh.yebServe.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzh.yebServe.pojo.ResultBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author wzh
 * @create 2022/11/9 11:18
 * @Description: 自定义授权异常处理
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            ResultBean error = ResultBean.error("尚未登录，请先登录");
            error.setCode(401);
            writer.write(new ObjectMapper().writeValueAsString(error));
            writer.flush();
            writer.close();
    }
}
